package com.alan.netty.nio.channels;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

/**
 * @author weiBin
 * @date 2018/11/7
 */
public class DatagramChannelReceive {
    public static void main(String[] args) throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.bind(new InetSocketAddress(1234));
        System.out.println("服务器端口1234启动：");
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        byte[] bytes;
        while (true) {
            buffer.clear();
            SocketAddress socketAddress = datagramChannel.receive(buffer);
            buffer.flip();
            bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            System.out.println(String.format("客户端%s 输入%s", socketAddress.toString(), new String(bytes, "UTF-8")));
            sendBack(socketAddress, datagramChannel);
        }
    }

    public static void sendBack(SocketAddress socketAddress, DatagramChannel datagramChannel) throws IOException {
        String message = "I has receive your message";
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(message.getBytes("utf-8"));
        buffer.flip();
        datagramChannel.send(buffer, socketAddress);
    }
}
